package kr.hkit.androidcomplete03.ch28;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch28.common.Item;
import kr.hkit.androidcomplete03.ch28.common.MyAdapter;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class SAXParserEx extends Activity {

	ListView lists;
	ProgressDialog progressDlg; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		lists = (ListView)findViewById(R.id.orderListView);
		new ParsingXml().execute("order.xml"); 
	}	
	
	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> { 
		
		 protected void onPreExecute() { 
			 Log.d("TAG", "SAXParserEx _ onPreExecute()");
		 progressDlg = ProgressDialog.show(SAXParserEx.this, "Wait", 
		 "order.xml & order.json Making ..."); 
		 } 
		 
		 protected ArrayList<Item> doInBackground(String... params) { 
			 Log.d("TAG", "SAXParserEx _ doInBackground()");
			 StringBuffer sb = new StringBuffer(); 
			 String str = null; 
			 SaxHandler handler = null;
			 BufferedReader br = null;
			 try {
				br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str = br.readLine()) != null){
					sb.append(str);
				}
				
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser parser = factory.newSAXParser();
				XMLReader reader = parser.getXMLReader();
				
				handler = new SaxHandler();
				reader.setContentHandler(handler);
				
				InputStream is = new ByteArrayInputStream(sb.toString().getBytes("utf-8"));
				reader.parse(new InputSource(is));
				
			 } catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} finally{
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			 
			return handler.arLists; 
		 }

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			Log.d("TAG", "SAXParserEx _ onPostExecute()");
			MyAdapter adapter = new MyAdapter(SAXParserEx.this, R.layout.listrow, result);
			lists.setAdapter(adapter);
			progressDlg.dismiss();
		}
	}
	
	private class SaxHandler extends DefaultHandler{

		ArrayList<Item> arLists = new ArrayList<>();
		Item item;
		boolean initItem;
		
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			Log.d("TAG", "startDocument()");
		}

		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
			Log.d("TAG", "endDocument()");
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			Log.d("TAG", "startElement()");
			
			if(localName.equalsIgnoreCase("item")){
				// 새로운 elements가 시작하려면
				initItem = true;
				item = new Item();
			}
			
			// 해당 elements 속성이 정해져 있다면
			if(attributes.getLength() > 0){
				for(int i=0; i<attributes.getLength(); i++){
					if(attributes.getLocalName(i).equalsIgnoreCase("price")){
						item.setItemPrice(Integer.parseInt(attributes.getValue(i)));
					} else{
						item.setItemMaker(attributes.getValue(i));
					}
				}
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);
			Log.d("TAG", "endElement()");
		}

		// <item maker = "samsung" price = "21000"> 여기에 왔을 때
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			super.characters(ch, start, length);
			Log.d("TAG", "characters()");
			
			if(initItem){
				item.setItemName(new String(ch, start, length));
				arLists.add(item);
				initItem = false;
			}
		}
	}

}
